#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

static int  checkipdeny (lua_State *L)
{
	const char *sour = lua_tostring(L,1);
	const char *area = lua_tostring(L,2);
	char *buf;
	char *buffernumber;
	struct in_addr addr1,addr2;	
	if (!inet_aton(sour,&addr1))
	{
		lua_pushnumber(L,1);
		return 1;
	}
	buffernumber = (char *) malloc(30);
	buf = strstr(area,"/");
	strcpy(buffernumber,buf+1);   
	int ofsize,ipaddr,iparea;
	ofsize = atoi(buffernumber);
	if (ofsize == 0 ) 
	{
		free(buffernumber);
		buffernumber = NULL;
		lua_pushnumber(L,2);
		return 1;
	}
	memset(buffernumber,'\0',30);
	strncpy(buffernumber,area,abs(area-buf));	
	if (!inet_aton(buffernumber,&addr2))
	{

		free(buffernumber);
		buffernumber = NULL;
		lua_pushnumber(L,3);
		return 1;
	}
	ofsize = 32 - ofsize;
	ipaddr = addr1.s_addr << ofsize ;
	iparea = addr2.s_addr << ofsize ;
	if (ipaddr == iparea )
	{

		free(buffernumber);
		buffernumber = NULL;
		lua_pushnumber(L,0);
		return 1 ;
	}
	else {

		free(buffernumber);
		buffernumber = NULL;
		lua_pushnumber(L,4);
		return 1;
	}
}



static const struct luaL_reg denyip[] = {
	{"checkdeny",checkipdeny},
	{0,0}
};

int luaopen_denyip(lua_State *L)
{
	luaL_openlib (L,"denyip",denyip,0);
	return 1;
}

